<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\Item;
use DB;
use Illuminate\Http\Request;

class ItemsController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    /**
     * 查询所有
     */
    public function all(Request $request)
    {
        $page = $this->page($request);
        $data = DB::table('items')->select('id', 'name', 'status')->skip($page['skip'])->take($page['take'])->get();
        $count = DB::table('items')->count();
        $data = array('count' => $count, 'item' => $data);
        return $this->respond('get_ok', $data);
    }
    //获取单条记录
    public function get($id)
    {
        $data = Item::find($id);
        if (!empty($data)) {
            return $this->respond('get_ok', $data);
        }
        return $this->respond('get_error');
    }
    //新增保存
    public function add(Request $request)
    {
        $m = new Item();
        $name = $request->input('name');
        $status = $request->input('status');
        if (empty($name) || empty($status)) {
            return $this->respond('empty_error');
        }
        $m->name = $name;
        $m->status = $status;
        $result = $m->save();
        if ($result) {
            $file = $request->file('file');
            if (!empty($file)) {
                $newFileName = md5(time() . rand(0, 10000)) . '.' . $file->getClientOriginalExtension();
                $savePath = 'uploads/' . date('Ym', time());
                $request->file('file')->move($savePath, $newFileName);
            }
            return $this->respond('add_ok');
        }
        return $this->respond('add_error');
    }
    //更新保存
    public function put(Request $request, $id)
    {
        $m = new Item();
        $model = $m::find($id);
        if (empty($model)) {
            return $this->respond('get_error');
        }
        $name = $request->input('name');
        $status = $request->input('status');
        if (empty($name) || empty($status)) {
            return $this->respond('empty_error');
        }
        $model->name = $name;
        $model->status = $status;
        $result = $model->save();
        if ($result) {
            return $this->respond('update_ok');
        }
        return $this->respond('update_error');
    }
    //删除
    public function remove($id)
    {
        $m = new Item();
        if (empty($m::find($id))) {
            return $this->respond('get_error');
        }
        $result = $m::destroy($id);
        if ($result) {
            return $this->respond('delete_ok');
        }
        return $this->respond('delete_error');
    }
}
